<?php
namespace app\scodetrace\model;

use \think\Model;
use \think\facade\Cache;
use \app\scodetrace\encoder\TcodeEncoder;

class TraceLog extends \app\common\model\Base{
	protected $table='xl_trace_log';

	protected $_AllowEnable=false;
	protected $_AllowGetChild=true;
	protected $_AllowDelete=false;

	protected $insert=['submitter_id','submitter_time'];
	protected $append=['submitter','area'];
	protected $hidden=['submitter_id','pid','id'];
	protected $_RejectCreate = ['submitter_time','submitter'];
  protected $_RejectUpdate = ['submitter_time','submitter'];
	use \app\common\model\BaseSubmitter;

	protected $Cache = null;

	public function getLogIds($logTailId) {
		$cache = null;
		$ids = [];
		$pid = $logTailId;
		if (!$this->Cache)
			$this->Cache = Cache::store('stlog');

		while (true) {
			if ($cache = $this->Cache->get($pid)) {
				break;
			}
			$pid = db($this->table)->where('id',$pid)->value('pid');
			if (!$pid) {
				$ids = array_reverse($ids);
				break;
			} else
				array_push($ids, $pid);
		}
		if ($cache)
			$head = $cache;
		else
			$head = [];

		foreach ($ids as &$v) {
			$this->Cache->set($v, $head);
			array_push($head, $v);
			unset($v);
		}

		array_push($head, $logTailId);
		return $head;
	}

	public function batch() {
		return $this->belongsTo("Batch");
	}

	public function operator() {
		return $this->belongsTo("admin/AdminUser",'user_id')->field(['realname']);
	}

	public function getAreaAttr($value,$data) {
		if ($data['area_id']) {
			if ($area = model('baseinfo/Area')->get($data['area_id'])) {
				return $area->getAttr('full_name');
			}
		}
		return null;

	}

	public static function logOne($pid,$logText,$area_id,$result) {
		$logModel=model('TraceLog');
		$logModel->setAttr('id', null);
		if ($logModel->isUpdate(false)->save([
			'logtext'=>$logText,
			'area_id'=>$area_id,
			'result'=>$result,
			'pid'=>$pid
			])==1) {
			return $logModel->id;
		} else {
			$this->error= '写入log失败';
			return 0;
		}
	}

	public function getLog($tcode) {
		$id = TcodeEncoder::getInstance()->decode($tcode);
		if ($model=model('Scode')->get($id)) {
			$ids = $this->getLogIds($model->log_id);
			if (count($ids)) {
				return $this->where('id','in',$ids)->select();
			} else {
				return null;
			}
		} else {
			return null;
		}

	}
}

?>